package renkosoft;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

import static cs.java.lang.Lang.exception;
import static cs.java.lang.Lang.info;

import cs.java.lang.Lang;



import rensoft.jre.JreLangCoreImpl;
import rensoft.jre.io.DirImpl;
import rensoft.jre.io.File;
import rensoft.jre.io.FileImpl;



public class SnapshotCreator {

  public static final void main(String[] args) {
    new SnapshotCreator(args);
  }

  private final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);

  private final DirImpl targetDir;

  public SnapshotCreator(String[] args) {
    Lang.initialize(new JreLangCoreImpl());
    info((Object[]) args);
    File urlList = new FileImpl(args[0].trim().replaceAll(" ", "\\ "));
    info("urllist", urlList);
    targetDir = new DirImpl(args[1].trim().replaceAll(" ", "\\ "));
    info("targetDir", targetDir);
    for (String url : urlList.lines()) {
      String shot = createSnapshot(url.trim());
      String filename = createFileName(url.trim());
      File targetFile = new FileImpl(targetDir, filename);
      targetFile.write(shot);
    }
  }

  private String createFileName(String url) {
    String filename = "SNAPSHOT";
    boolean hasArguments = url.charAt(url.length() - 1) != '/';
    if (hasArguments) {
      String[] urlPathSplit = url.trim().split("/");
      String arguments = urlPathSplit[urlPathSplit.length - 1];
      filename += arguments.replace("=", "EQUALS").substring(2);
    }
    return filename + ".html";
  }

  private String createSnapshot(String url) {
    webClient.setCssEnabled(false);
    webClient.setThrowExceptionOnScriptError(false);
    webClient.setThrowExceptionOnFailingStatusCode(false);
    webClient.setJavaScriptEnabled(true);
    HtmlPage page = null;
    try {
      page = webClient.getPage(url);
    } catch (Exception e) {
      throw exception(e);
    }
    webClient.waitForBackgroundJavaScript(5000);

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("<hr />\n");
    stringBuilder
        .append("<center><h3>You are viewing a non-interactive page that is intended for the crawler.  ");
    stringBuilder.append("You probably want to see this page: <a href=\"" + url + "\">" + url
        + "</a></h3></center>\n");
    stringBuilder.append("<hr />\n");

    stringBuilder.append(page.asXml());
    webClient.closeAllWindows();
    return stringBuilder.toString();
  }
}
